<template>
  <div >
    <el-tabs v-model="activeTab" style="width: 1200px;
    height:auto;
    min-height: 150px;
    margin: 0 auto;
    margin-top: 20px;
    overflow-y: hidden;
    padding-left: calc(100vw - 100%);
    background-color: rgba(255, 255, 255, 0.37);">
      <el-tab-pane   label="年检申请" name="AS">
        <div v-if="loading1">数据加载中...</div>
        <div v-if="!loading1">
          <div v-if="ASApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState1" placeholder="未审批" @change="getASApplies" style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState1 === 0" type="primary" @click="approveSelectedApplies('approve',2)">一键批准所选</el-button>
              <el-button v-if="ApprovalState1 === 0" type="primary" @click="approveSelectedApplies('reject',2)">一键拒绝所选</el-button>
            </div>
            <el-table
                ref="ASTable"
                :data="filteredAS"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
                style="width: 1120px"
            >
              <el-table-column type="selection" width="55" v-if="ApprovalState1 === 0"></el-table-column>
              <el-table-column
                  type="index"
                  width="50">
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="申请者ID" ></el-table-column>
              <el-table-column prop="uname" label="申请者" ></el-table-column>
              <el-table-column prop="cname" label="社团" :filters="clubFilters1" :filter-method="filterByClub1">
                <template #default="scope">
                  <span>{{ scope.row.cname }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="CPName" label="年检主题" :filters="ASFilters" :filter-method="filterByAS">
                <template #default="scope">
                  <span>{{ scope.row.CPName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="申请附件">
                <template #default="{ row }">
                  <div style="display: flex;align-items:center;">
                    <el-icon><Document /></el-icon>
                    <a :href=row.file.FileUrl  @click.prevent="handleDownload(row.file.FileUrl, row.file.Filename)">{{ row.file.Filename }}</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="ApprovalState1 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog1(row, 'approve')" type="primary" style="margin-right: 5px;">批准</el-button>
                    <el-button @click="openDialog1(row, 'reject')" type="danger">拒绝</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState1 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 3||row.approval_state ===5" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 4||row.approval_state ===6" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible1"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="annualsurvey.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelASApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm1">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-if="ASApplies.length==0">
            暂时没有年检申请
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="评优申请" name="CE">
        <div v-if="loading2">数据加载中...</div>
        <div v-if="!loading2">
          <div v-if="CEApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState2"  placeholder="未审批" @change="getCEApplies"  style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState2 === 0" type="primary" @click="approveSelectedApplies('approve',3)">一键批准所选</el-button>
              <el-button v-if="ApprovalState2 === 0" type="primary" @click="approveSelectedApplies('reject',3)">一键拒绝所选</el-button>
            </div>

            <el-table
                ref="CETable"
                :data="filteredCE"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
                style="width: 1120px"
            >
              <el-table-column type="selection" width="55" v-if="ApprovalState2 === 0"></el-table-column>
              <el-table-column
                  type="index"
                  width="50">
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="申请者ID" ></el-table-column>
              <el-table-column prop="uname" label="申请者" ></el-table-column>
              <el-table-column prop="cname" label="社团" :filters="clubFilters2" :filter-method="filterByClub2">
                <template #default="scope">
                  <span>{{ scope.row.cname }}</span>
                </template>
              </el-table-column>
              <el-table-column label="申请附件">
                <template #default="{ row }">
                  <div style="display: flex;align-items:center;">
                    <el-icon><Document /></el-icon>
                    <a :href=row.file.FileUrl  @click.prevent="handleDownload(row.file.FileUrl, row.file.Filename)">{{ row.file.Filename }}</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="CEName" label="评优主题" :filters="CEFilters" :filter-method="filterByCE">
                <template #default="scope">
                  <span>{{ scope.row.CEName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="ApprovalState2 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog2(row, 'approve')" type="primary" style="margin-right: 5px;">批准</el-button>
                    <el-button @click="openDialog2(row, 'reject')" type="danger">拒绝</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState2 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 3||row.approval_state ===5" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 4||row.approval_state ===6" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible2"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="clubexamine.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelCEApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm2">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-if="CEApplies.length==0">
            暂时没有评优申请
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="创建社团申请" name="createclub">
        <div v-if="loading3">数据加载中...</div>
        <div v-if="!loading3">
          <div v-if="CreateClubApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState3" placeholder="未审批" @change="getCreateClubApplies" style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState3 === 0" type="primary" @click="approveSelectedApplies('approve',4)">一键批准所选</el-button>
              <el-button v-if="ApprovalState3 === 0" type="primary" @click="approveSelectedApplies('reject',4)">一键拒绝所选</el-button>
            </div>
            <el-table
                ref="CreateClubTable"
                :data="filteredCreateClub"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
                style="width: 1120px"
            >
              <el-table-column type="expand">
                <template #default="props">
                  <el-form label-position="left" inline class="CCtable-expand" >
                    <el-form-item label="申请人ID:"><span>{{ props.row.uid }}</span></el-form-item>
                    <el-form-item label="申请人:"><span>{{ props.row.LeaderName }}</span></el-form-item>
                    <el-form-item label="申请人邮箱:"><span>{{ props.row.Mailbox }}</span></el-form-item>
                    <el-form-item label="申请人联系电话:"><span>{{ props.row.Phone }}</span></el-form-item>

                    <el-form-item label="社团:"><span>{{ props.row.cname }}</span></el-form-item>
                    <el-form-item label="社团宗旨:"><span>{{ props.row.aim }}</span></el-form-item>

                    <el-form-item style="width:30%"  label="所在校区:"><span>{{getCampusText(props.row.campus) }}</span></el-form-item>
                    <el-form-item style="width:30%" label="社团类型:"><span>{{getTypeText(props.row.type) }}</span></el-form-item>
                    <el-form-item style="width:30%" label="所属单位:"><span>{{ props.row.unit }}</span></el-form-item>

                    <el-form-item style="width:30%" label="业务指导老师ID:"><span>{{ props.row.TeacherID }}</span></el-form-item>
                    <el-form-item style="width:30%" label="业务指导老师:"><span>{{ props.row.TeacherName }}</span></el-form-item>
                    <el-form-item style="width:30%" label="业务指导老师联系方式:"><span>{{ props.row.TeachePhone }}</span></el-form-item>

                    <el-form-item style="width:30%" label="行政指导老师ID:"><span>{{ props.row.AdminTeacherID }}</span></el-form-item>
                    <el-form-item style="width:30%" label="行政指导老师:"><span>{{ props.row.AdminTeacherName }}</span></el-form-item>
                    <el-form-item style="width:30%" label="行政指导老师联系方式:"><span>{{ props.row.AdminTeacherPhone }}</span></el-form-item>

                    <el-form-item  style="width:100%"  label="社团介绍:"><span>{{ props.row.Introduction }}</span></el-form-item>

                  </el-form>
                </template>
              </el-table-column>
              <el-table-column type="selection" width="55" v-if="ApprovalState3 === 0"></el-table-column>
              <el-table-column
                  type="index"
                  width="50">
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="申请人ID" ></el-table-column>
              <el-table-column prop="LeaderName" label="申请人" ></el-table-column>
              <el-table-column prop="cname" label="社团名称"></el-table-column>
              <el-table-column prop="aim" label="社团宗旨" ></el-table-column>
              <el-table-column label="申请附件">
                <template #default="{ row }">
                  <div style="display: flex;align-items:center;">
                    <el-icon><Document /></el-icon>
                    <a :href=row.file.FileUrl  @click.prevent="handleDownload(row.file.FileUrl, row.file.Filename)">{{ row.file.Filename }}</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="ApprovalState3 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog3(row, 'approve')" type="primary" style="margin-right: 5px;">批准</el-button>
                    <el-button @click="openDialog3(row, 'reject')" type="danger">拒绝</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState3 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 3||row.approval_state ===5" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 4||row.approval_state ===6" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible3"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="createclub.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelcreateclubApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm3">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-if="CreateClubApplies.length==0">
            暂时没有创建社团申请
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="举办活动申请" name="createactivity">
        <div v-if="loading4">数据加载中...</div>
        <div v-if="!loading4">
          <div v-if="CreateActivityApplies.length>0" style="display: flex;flex-direction: column;">
            <div style="display: flex;justify-content:flex-start;align-items:center;margin:10px">
              <div style="margin-left:10px;margin-right:10px ">
                <el-select v-model="ApprovalState4" placeholder="未审批" @change="getCreateActivityApplies" style="width:150px;marigin:10px">
                  <el-option label="未审批" :value="0"></el-option>
                  <el-option label="已审批" :value="1"></el-option>
                </el-select>
              </div>
              <el-button v-if="ApprovalState4 === 0" type="primary" @click="approveSelectedApplies('approve',5)">一键批准所选</el-button>
              <el-button v-if="ApprovalState4 === 0" type="primary" @click="approveSelectedApplies('reject',5)">一键拒绝所选</el-button>
            </div>
            <el-table
                ref="CreateActivityTable"
                :data="filteredCreateActivity"
                :default-sort="{ prop: 'applyTime', order: 'descending' }"
            >
              <el-table-column type="expand">
                <template #default="props">
                  <el-form label-position="left" inline class="CCtable-expand" >
                    <el-form-item label="申请人ID:"><span>{{ props.row.uid }}</span></el-form-item>
                    <el-form-item label="申请人:"><span>{{ props.row.uname }}</span></el-form-item>
                    <el-form-item label="活动名称:"><span>{{ props.row.aname }}</span></el-form-item>
                    <el-form-item label="开展该活动的社团:"><span>{{ props.row.cname }}</span></el-form-item>

                    <el-form-item style="width:30%" label="活动类型:"><span>{{getTypeText(props.row.type) }}</span></el-form-item>
                    <el-form-item style="width:30%"  label="所在校区:"><span>{{getCampusText(props.row.campus) }}</span></el-form-item>
                    <el-form-item style="width:30%" label="开展地点:"><span>{{ props.row.place }}</span></el-form-item>

                    <el-form-item label="报名开始时间:"><span>{{ props.row.apply_stime }}</span></el-form-item>
                    <el-form-item label="报名结束时间:"><span>{{ props.row.apply_etime }}</span></el-form-item>
                    <el-form-item  label="活动开始时间:"><span>{{ props.row.stime }}</span></el-form-item>
                    <el-form-item  label="活动结束时间:"><span>{{ props.row.etime }}</span></el-form-item>

                    <el-form-item  label="活动面向对象:"><span>{{getPermitText(props.row.permit) }}</span></el-form-item>
                    <el-form-item  label="报名要求:"><span>{{ props.row.require }}</span></el-form-item>

                    <el-form-item  style="width:100%"  label="活动内容:"><span>{{ props.row.content }}</span></el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column type="selection" width="55" v-if="ApprovalState4 === 0"></el-table-column>
              <el-table-column
                  type="index"
                  width="50">
              </el-table-column>
              <el-table-column style="min-width: 200px;" prop="applyTime" label="申请时间" sortable :formatter="DatetoUser"></el-table-column>
              <el-table-column prop="uid" label="用户ID" ></el-table-column>
              <el-table-column prop="uname" label="用户名" ></el-table-column>
              <el-table-column prop="aname" label="活动" ></el-table-column>
              <el-table-column prop="cname" label="开展的社团" :filters="clubFilters3" :filter-method="filterByClub3">
                <template #default="scope">
                  <span>{{ scope.row.cname }}</span>
                </template>
              </el-table-column>
              <el-table-column label="申请附件">
                <template #default="{ row }">
                  <div style="display: flex;align-items:center;">
                    <el-icon><Document /></el-icon>
                    <a :href=row.file.FileUrl  @click.prevent="handleDownload(row.file.FileUrl, row.file.Filename)">{{ row.file.Filename }}</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="ApprovalState4 === 0">
                <template v-slot="{ row }">
                  <div style="display: flex; align-items: center;">
                    <el-button @click="openDialog4(row, 'approve')" type="primary" style="margin-right: 5px;">批准</el-button>
                    <el-button @click="openDialog4(row, 'reject')" type="danger">拒绝</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="审批结果" v-if="ApprovalState4 === 1" :filters="approvalFilters"
                               :filter-method="filterByApprovalResult">
                <template v-slot="{ row }">
                  <el-tag v-if="row.approval_state === 3||row.approval_state ===5" type="success">已通过</el-tag>
                  <el-tag v-if="row.approval_state === 4||row.approval_state ===6" type="danger">已拒绝</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog   v-model="dialogVisible4"  title="备注" @close="handleclose">
              <el-input type="textarea" v-model="createactivity.remark"></el-input>
              <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancelcreateactivityApprove">取 消</el-button>
                <el-button type="primary" @click="submitForm4">确 定</el-button>
              </span>
              </template>
            </el-dialog>
          </div>
          <div v-if="CreateActivityApplies.length==0">
            暂时没有创建活动申请
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {onMounted, reactive, ref} from 'vue';
import axios from "axios";
import {useStore} from "vuex";
import {ElMessage} from "element-plus";
import {downloadFile} from "@/utils/fileTool";

export default {
  methods: {
    handleDownload(fileUrl, fileName) {
      downloadFile(fileUrl,fileName)
    },
  },
  setup() {
    const activeTab = ref('AS');
    const store = useStore();
    const ASTable = ref(null);
    const CETable=ref(null);
    const CreateClubTable=ref(null);
    const CreateActivityTable=ref(null);

    const loading1=ref(true);
    const loading2=ref(true);
    const loading3=ref(true);
    const loading4=ref(true);

    const ASApplies= ref([]);const filteredAS=ref([]);
    const clubFilters1 = ref([]);
    const dialogVisible1 = ref(false);
    const ApprovalState1=ref(0);


    const CEApplies = ref([]); const filteredCE=ref([]);
    const CEFilters   = ref([]);const ASFilters   = ref([]);
    const dialogVisible2 = ref(false);
    const ApprovalState2=ref(0);


    const CreateClubApplies = ref([]); const filteredCreateClub=ref([]);
    const clubFilters3   = ref([]);
    const dialogVisible3 = ref(false);
    const ApprovalState3=ref(0);

    const CreateActivityApplies = ref([]); const filteredCreateActivity=ref([]);
    const clubFilters4   = ref([]);
    const dialogVisible4 = ref(false);
    const ApprovalState4=ref(0);

    const getTypeText=(type)=> {
      switch (type) {
        case 1:
          return '思想政治类';
        case 2:
          return '学术科技类';
        case 3:
          return '体育竞技类';
        case 4:
          return '志愿公益类';
        case 5:
          return '文化艺术类';
        default:
          return '';
      }
    };
    const getCampusText=(campus)=> {
      switch (campus) {
        case 1:
          return '南校区';
        case 2:
          return '北校区';
        case 3:
          return '珠海校区';
        case 4:
          return '深圳校区';
        case 5:
          return '东校区';
        case 6:
          return '五校园'
        default:
          return '';
      }
    };
    const getPermitText=(permit)=> {
      if(permit==0){
        return '仅限社团内部成员报名';
      }else if(permit==1){
        return '所有用户均可报名';
      }else{
        return '';
      }
    };

    const approvalFilters = ref([
      { text: '全部', value: 0 },
      { text: '已通过', value: 1 },
      { text: '已拒绝', value: 2 }
    ]);

    const filterByApprovalResult = (value, row) => {
      if (value === 0) return true;
      if (value === 1) return row.approval_state === 3 || row.approval_state === 5;
      if (value === 2) return  row.approval_state === 4 || row.approval_state === 6;
      return false;
    };

    const formatDate=(time)=> {
      var year = time.getFullYear(); // 年
      var month = (time.getMonth() + 1).toString().padStart(2, '0'); // 月
      var date = time.getDate().toString().padStart(2, '0'); // 日
      var hour = time.getHours().toString().padStart(2, '0'); // 时
      var minute = time.getMinutes().toString().padStart(2, '0'); // 分
      var second = time.getSeconds().toString().padStart(2, '0'); // 秒
      return (
          year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
      )
    };
    const DatetoUser = (row, column) => {
      const date = new Date(row[column.property]);
      const year = date.getUTCFullYear();
      const month = (date.getUTCMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以要加1
      const day = date.getUTCDate().toString().padStart(2, '0');
      const hours = date.getUTCHours().toString().padStart(2, '0'); // 获取小时
      const minutes = date.getUTCMinutes().toString().padStart(2, '0'); // 获取分钟
      const seconds = date.getUTCSeconds().toString().padStart(2, '0'); // 获取秒数
      return `${year}-${month}-${day}  ${hours}:${minutes}:${seconds}`;
    };



    const annualsurvey = reactive({
      action: '',
      remark: '',
      row: null
    });
    const clubexamine= reactive({
      action: '',
      remark: '',
      row: null
    });
    const createclub = reactive({
      action: '',
      remark: '',
      row: null
    });
    const createactivity = reactive({
      action: '',
      remark: '',
      row: null
    });
    // 打开对话框，每种申请不一样
    const openDialog1 = (row, action) => {
      annualsurvey.action = action;
      annualsurvey.row = row;
      dialogVisible1.value = true;
    }
    const openDialog2 = (row, action) => {
      clubexamine.action = action;
      clubexamine.row = row;
      dialogVisible2.value = true;
    }
    const openDialog3 = (row, action) => {
      createclub.action = action;
      createclub.row = row;
      dialogVisible3.value = true;
    }
    const openDialog4 = (row, action) => {
      createactivity.action = action;
      createactivity.row = row;
      dialogVisible4.value = true;
    }

    // 提交表单,每种申请不一样
    const submitForm1 = async () => {
      dialogVisible1.value = false;
      try {
        await approveApplication(annualsurvey.row, annualsurvey.remark,annualsurvey.action, 2);
        if (annualsurvey.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (annualsurvey.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      annualsurvey.remark='';
    }
    const cancelASApprove=()=>{
      dialogVisible1.value=false;
      annualsurvey.remark='';
    }

    const submitForm2 = async () => {
      dialogVisible2.value = false;
      try {
        await approveApplication(clubexamine.row, clubexamine.remark,clubexamine.action, 3);
        if (clubexamine.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (clubexamine.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      clubexamine.remark='';
    }
    const cancelCEApprove=()=>{
      dialogVisible2.value=false;
      clubexamine.remark='';
    }

    const submitForm3 = async () => {
      dialogVisible3.value = false;
      try {
        await approveApplication(createclub.row, createclub.remark,createclub.action, 4);
        if (createclub.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (createclub.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      createclub.remark='';
    }
    const cancelcreateclubApprove=()=>{
      dialogVisible3.value=false;
      createclub.remark='';
    }
    const submitForm4 = async () => {
      dialogVisible4.value = false;
      try {
        await approveApplication(createactivity.row, createactivity.remark,createactivity.action, 5);
        if (createactivity.action === 'approve') {
          ElMessage.success('申请已批准');
        } else if (createactivity.action === 'reject') {
          ElMessage.success('申请已拒绝');
        }
      } catch (error) {
        ElMessage.error("申请审批失败")
      }
      createactivity.remark='';
    }
    const cancelcreateactivityApprove=()=>{
      dialogVisible4.value=false;
      createactivity.remark='';
    }

    const approveSelectedApplies=async (action,kind) => {
      let selectedRows = [];
      if (kind === 2){
        selectedRows = ASTable.value?.getSelectionRows() || [];
      }else if(kind === 3){
        selectedRows = CETable.value?.getSelectionRows() || [];
      }else if(kind === 4){
        selectedRows = CreateClubTable.value?.getSelectionRows() || [];
      }else if(kind === 5){
        selectedRows = CreateActivityTable.value?.getSelectionRows() || [];
      }
      if (selectedRows.length === 0) {
        ElMessage.warning('请先选择要审批的申请');
        return;
      }
      let successCount = 0;
      let failureCount = 0;
      for (const row of selectedRows) {
        try {
          await approveApplication(row, '', action, kind);
          successCount++;
        } catch (error) {
          failureCount++;
        }
      }
      console.log("successCount",successCount)
      console.log("failureCount",failureCount)
      if (successCount > 0) {
        ElMessage.success(`成功审批 ${successCount} 个申请`);
      }

      if (failureCount > 0) {
        ElMessage.error(`有 ${failureCount} 个申请审批失败`);
      }
    }
    // 生成社团筛选项,根据社团名称筛选方法
    function generateclubFilters1() {
      const clubs = new Set(filteredAS.value.map(app => app.cname));
      clubFilters1.value = Array.from(clubs).map(club=> ({ text: club, value: club }));
    }
    const filterByClub1=(value, row)=>{
      return row.cname === value;
    }

    function generateASFilters() {
      const clubs = new Set(filteredAS.value.map(app => app.CPName));
      ASFilters.value = Array.from(clubs).map(club=> ({ text: club, value: club }));
    }
    const filterByAS=(value, row)=>{
      return row.CPName === value;
    }
    function generateCEFilters() {
      const clubs = new Set(filteredCE.value.map(app => app.CEName));
      CEFilters.value = Array.from(clubs).map(club=> ({ text: club, value: club }));
      console.log("CEFilters.value",CEFilters.value)
    }
    const filterByCE=(value, row)=>{
      return row.CEName === value;
    }
    function generateclubFilters3() {
      const clubs = new Set(filteredCreateClub.value.map(app => app.cname));
      clubFilters3.value = Array.from(clubs).map(club => ({ text: club, value: club }));
    }
    const filterByClub3=(value, row)=>{
      return row.cname === value;
    }

    function generateclubFilters4() {
      const clubs = new Set(filteredCreateActivity.value.map(app => app.cname));
      clubFilters3.value = Array.from(clubs).map(club => ({ text: club, value: club }));
    }
    const filterByClub4=(value, row)=>{
      return row.cname === value;
    }

    // 批准申请方法，适用于每种申请
    const approveApplication = async (row, remark,action,kind) => {
      const formData = new FormData()
      var getTime = new Date().getTime(); //获取到当前时间戳
      var time = new Date(getTime); //创建一个日期对象
      var currenttime=formatDate(time)
      formData.append('permission',store.state.userinfo.permission)
      formData.append('kind',kind)
      formData.append('id',row.id)
      formData.append("action",action)
      formData.append('apply_id',row.apply_id)
      formData.append('uid',row.uid)
      formData.append('aid',row.aid)
      formData.append('cid',row.cid)
      formData.append('remark',remark)
      formData.append('approval_time',currenttime)
      formData.append('cname',row.cname)
      formData.append('aname',row.aname)
      formData.append('approver',store.state.userinfo.account)
      try {
        const response = await axios.post('/api/approval/ApproveApplies', formData);
        if (kind === 2) {
          filteredAS.value = filteredAS.value.filter(club => club.id !== row.id);
        } else if (kind === 3) {
          filteredCE.value = filteredCE.value.filter(activity => activity.id !== row.id);
        } else if (kind === 4) {
          filteredCreateClub.value = filteredCreateClub.value.filter(createclub => createclub.id !== row.id);
        } else if (kind === 5) {
          filteredCreateActivity.value = filteredCreateActivity.value.filter(createactivity => createactivity.id !== row.id);
        }

        console.log(response);
      } catch (error) {
        console.error(error);
        throw new Error('审批失败');
      }
    }
    // 获取年检申请
    const getASApplies=async() => {
      loading1.value=true;
      let permission=store.state.userinfo.permission
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/ASApplies', {
        params: {
          account: store.state.userinfo.account,
          permission:store.state.userinfo.permission
        }
      })
          .then(response => {
            if(response.data.data.asApplies){
              ASApplies.value = response.data.data.asApplies;
              if(permission==2){
                filteredAS.value = ASApplies.value.filter(asApplies => {
                  if(ApprovalState1.value==0) return asApplies.approval_state === 0;
                  else return asApplies.approval_state === 3 || asApplies.approval_state === 4;
                });
              }else{
                filteredAS.value = ASApplies.value.filter(asApplies => {
                  if(ApprovalState1.value==0) return asApplies.approval_state === 3;
                  else return asApplies.approval_state === 5 || asApplies.approval_state === 6;
                });
              }
              generateclubFilters1();
              generateASFilters()
            }

          })
          .catch(function (err) {
            ElMessage.error("获得社团年检申请失败")
            console.log('获得年检审批失败' + err)
          })
          .finally(() => {
            loading1.value = false;
          });
    };
    // 获取评优申请
    const getCEApplies =async() => {
      loading2.value = true;
      let permission=store.state.userinfo.permission
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/CEApplies', {
        params: {
          account: store.state.userinfo.account,
          permission:store.state.userinfo.permission
        }
      })
          .then(response => {
            console.log("py响应数据", response);
            if(response.data.data.ceApplies) {
              CEApplies.value = response.data.data.ceApplies;
              console.log("获得加评优审批", response.data.data);
              if (permission == 2) {
                filteredCE.value = CEApplies.value.filter(ceApplies => {
                  if (ApprovalState2.value == 0) return ceApplies.approval_state === 0;
                  else return ceApplies.approval_state === 3 || ceApplies.approval_state === 4;
                });
              } else {
                filteredCE.value = CEApplies.value.filter(ceApplies => {
                  if (ApprovalState2.value == 0) return ceApplies.approval_state === 3;
                  else return ceApplies.approval_state === 5 || ceApplies.approval_state === 6;
                });
              }
              generateCEFilters();
            }
            })
          .catch(function (err) {
              ElMessage.error("获得社团评优申请失败")
              console.log('获得加入评优审批失败????????' + err)
            }).finally(() => {
                loading2.value = false;
                });
    };
    // 获取创建社团申请
    const getCreateClubApplies =async() => {
      loading3.value = true;
      let permission=store.state.userinfo.permission
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/CreateClubApplies', {
        params: {
          account: store.state.userinfo.account,
          permission:store.state.userinfo.permission
        }
      })
          .then(response => {
            if(response.data.data.createclubs){
              CreateClubApplies.value = response.data.data.createclubs;
              console.log("获得创建社团审批",response.data.data);
              if(permission==2){
                filteredCreateClub.value = CreateClubApplies.value.filter(createclubs => {
                  if(ApprovalState3.value==0) return createclubs.approval_state === 0;
                  else return createclubs.approval_state === 3 || createclubs.approval_state === 4;
                });
              }else{
                filteredCreateClub.value = CreateClubApplies.value.filter(createclubs => {
                  if(ApprovalState3.value==0) return createclubs.approval_state === 3;
                  else return createclubs.approval_state === 5 || createclubs.approval_state === 6;
                });
              }
              generateclubFilters3();
            }
          })
          .catch(function (err) {
            ElMessage.error("获得创建社团申请失败")
            console.log('获得申请创建社团审批失败' + err)
          })
          .finally(() => {
            loading3.value = false;
          });
    };
    // 获取举办活动申请
    const getCreateActivityApplies =async() => {
      loading4.value = true;
      let permission=store.state.userinfo.permission
      console.log("account:",store.state.userinfo.account)
      axios.get('/api/approval/CreateActivityApplies', {
        params: {
          account: store.state.userinfo.account,
          permission:store.state.userinfo.permission
        }
      })
          .then(response => {
            if(response.data.data.createactivities){//不为null
              CreateActivityApplies.value = response.data.data.createactivities;
              console.log("获得举办活动审批",response.data.data);
              if(permission==2){
                filteredCreateActivity.value = CreateActivityApplies.value.filter(createactivities => {
                  if(ApprovalState4.value==0) return createactivities.approval_state === 0;
                  else return createactivities.approval_state === 3 || createactivities.approval_state === 4;
                });
              }else{
                filteredCreateActivity.value = CreateActivityApplies.value.filter(createactivities => {
                  if(ApprovalState4.value==0) return createactivities.approval_state === 3;
                  else return createactivities.approval_state === 5 || createactivities.approval_state === 6;
                });
              }
              generateclubFilters4();
            }
          })
          .catch(function (err) {
            ElMessage.error("获得举办活动申请失败")
            console.log('获得举办活动审批失败' + err)
          })
          .finally(() => {
            loading4.value = false;
          });
    };

    const handleclose=()=>{
      annualsurvey.remark='';
      clubexamine.remark='';
      createclub.remark='';
      createactivity.remark='';
    }

    onMounted(() => {
      getASApplies();
      getCEApplies();
      getCreateClubApplies();
      getCreateActivityApplies();
    });


    return {
      handleclose,
      activeTab,
      DatetoUser,formatDate,
      approvalFilters,filterByApprovalResult,
      approveApplication,
      getCampusText,
      getTypeText,
      getPermitText,
      loading1,loading2,loading3,loading4,
      CETable, CreateClubTable, ASTable,CreateActivityTable,
      filterByAS,filterByCE,
      ASFilters,CEFilters,
      ApprovalState1,
      ASApplies,filteredAS,
      getASApplies,
      annualsurvey,
      cancelASApprove,
      submitForm1,
      approveSelectedApplies,
      dialogVisible1,
      openDialog1,
      clubFilters1,filterByClub1,

      ApprovalState2,
      CEApplies,filteredCE,
      getCEApplies,
      clubexamine,
      cancelCEApprove,
      submitForm2,
      dialogVisible2,
      openDialog2,


      ApprovalState3,
      CreateClubApplies,filteredCreateClub,
      getCreateClubApplies,
      createclub,
      cancelcreateclubApprove,
      submitForm3,
      dialogVisible3,
      openDialog3,
      clubFilters3,filterByClub3,

      ApprovalState4,
      CreateActivityApplies,filteredCreateActivity,
      getCreateActivityApplies,
      createactivity,
      cancelcreateactivityApprove,
      submitForm4,
      dialogVisible4,
      openDialog4,
      clubFilters4,filterByClub4,

    };
  },
};
</script>

<style scoped>
.el-table {
  overflow-y: auto !important;
  overflow-x: auto !important;
}

.CCtable-expand {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.el-form-item span {/*改变信息颜色*/
  color: #606266;
}
.CCtable-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

</style>
